/*
 * @author Chris
 * @since 2023/1/28 19:58
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/1/28     Chris        the first version
 */
#include "reg51.h"

#define LCD1602_DB P0
#define LCD1602_RS P1_0
#define LCD1602_RW P1_1
#define LCD1602_EN P1_5

void LcdWaitReady() {
    LCD1602_DB = 0xFF;
    LCD1602_RS = 0;
    LCD1602_RW = 1;
    unsigned char stat;
    do {
        LCD1602_EN = 1;
        stat = LCD1602_DB;
        LCD1602_EN = 0;
    } while (stat & 0x80);
}

void LcdWriteCmd(unsigned char cmd) {
    LcdWaitReady();
    LCD1602_RS = 0;
    LCD1602_RW = 0;
    LCD1602_DB = cmd;
    LCD1602_EN = 1;
    LCD1602_EN = 0;
}

void LcdWriteData(unsigned char dat) {
    LcdWaitReady();
    LCD1602_RS = 1;
    LCD1602_RW = 0;
    LCD1602_DB = dat;
    LCD1602_EN = 1;
    LCD1602_EN = 0;
}

void LcdSetCursor(unsigned char x, unsigned char y) {
    LcdWriteCmd(0x80 | (x + (y == 0 ? 0x00 : 0x40)));
}

void InitLcd1602() {
    LcdWriteCmd(0x38);
    LcdWriteCmd(0x0C);
    LcdWriteCmd(0x06);
    LcdWriteCmd(0x01);
}

void Lcd1602ShowStr(unsigned char x, unsigned char y, unsigned char *buf, unsigned char len) {
    LcdSetCursor(x, y);
    while (len--) {
        LcdWriteData(*buf++);
    }
}

void LcdClearArea(unsigned char x, unsigned char y, unsigned char len) {
    LcdSetCursor(x, y);
    while (len--) {
        LcdWriteData(' ');
    }
}

void LcdClearFull() {
    LcdWriteCmd(0x01);
}